package com.tcl.aota.common.utils;

import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by kelong on 9/2/14.
 */
public class DateUtil {

    private final static Logger LOG = Logger.getLogger(DateUtil.class);

    /**
     * 时间转换为字符串
     *
     * @param format ：格式方式
     * @param date   ：时间
     * @return
     */
    public static String fomartDateToStr(String format, Date date) {
        String dateString = null;
        try {
            if (null != date) {
                SimpleDateFormat formatter = new SimpleDateFormat(format);
                dateString = formatter.format(date);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        return dateString;
    }

    /**
     * @param days
     * @return
     */
    public static String getBeforeDays(int days) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -days);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime());
    }

    /**
     * @param hours
     * @return
     */
    public static String getBeforeHours(int hours) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, -hours);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime());
    }

    /**从昨天开始推算前hours
     * @param hours
     * @return
     */
    public static String getBeforeHoursFromYeserday(int hours) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY,0);
        c.set(Calendar.MINUTE,0);
        c.set(Calendar.SECOND,0);
        c.add(Calendar.HOUR, -hours);
        return fomartDateToStr("yyyy-MM-dd HH:mm:ss",c.getTime());
    }

    /**
     * 从周1开始推算前几天(上周时间)
     * @param days
     * @return
     */
    public static String getBeforeDaysFromLastWeek(int days){
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_WEEK,1);
        c.set(Calendar.HOUR_OF_DAY,0);
        c.set(Calendar.MINUTE,0);
        c.set(Calendar.SECOND,0);
        c.add(Calendar.DATE, -(days-1));//（周一到周日
        return fomartDateToStr("yyyy-MM-dd HH:mm:ss",c.getTime());
    }

    /**
     * 从上月开始向前推算月份
     * @param months
     * @return
     */
    public static String getBeforeMonthsFromLastMonth(int months){
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_MONTH,1);
        c.set(Calendar.HOUR_OF_DAY,0);
        c.set(Calendar.MINUTE,0);
        c.set(Calendar.SECOND,0);
        c.add(Calendar.MONTH, -months);
        return fomartDateToStr("yyyy-MM-dd HH:mm:ss",c.getTime());
    }

    public static void main(String[] args){
        System.out.println(DateUtil.getBeforeDaysFromLastWeek(27));//2015-01-19 00:00:00,2015-01-19 03:00:00
//        System.out.println(DateUtil.getBeforeMonthsFromLastMonth(2));
    }

}
